package com.xd.core.api.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xd.common.base.CustomRowHeightColWidthHandler;
import com.xd.common.base.RowHeightColWidthModel;
import com.xd.common.constant.SysConstant;
import com.xd.common.util.SecurityUtil;
import com.xd.core.api.entity.RepaymentOrderInfo;
import com.xd.core.api.mapper.RepaymentOrderInfoMapper;
import com.xd.core.api.service.IRepaymentOrderInfoService;
import com.xd.core.bill.dto.OfflineRepaymentDetailQuery;
import com.xd.core.bill.vo.OfflineRepaymentDetailVo;
import com.xd.core.company.dto.HomeQueryDto;
import com.xd.core.company.vo.ReceiveCounts;
import com.xd.core.finance.dto.RepayManageDto;
import com.xd.core.finance.vo.RepayManageVo;
import com.xd.core.mission.entity.MissionCenterInfo;
import com.xd.core.mission.mapper.MissionCenterInfoMapper;
import com.xd.core.system.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 还款订单信息 服务实现类
 * </p>
 *
 * @author ZX
 * @since 2025-03-11
 */
@Service
public class RepaymentOrderInfoServiceImpl extends ServiceImpl<RepaymentOrderInfoMapper, RepaymentOrderInfo> implements IRepaymentOrderInfoService {
    @Autowired
    private RepaymentOrderInfoMapper repaymentOrderInfoMapper;
    @Autowired
    private ISysUserService iSysUserService;
    @Value("${image.localPathDir}")
    private String localPathDir;
    @Value("${image.exportFile}")
    private String exportFile;
    @Autowired
    private MissionCenterInfoMapper missionCenterInfoMapper;
    @Value("${aes.key}")
    private String aesKey;

    @Override
    public ReceiveCounts getReceiveCounts(HomeQueryDto query) {
        String companyType = SecurityUtil.getLoginCompany().getCompanyType();
        Integer companyId = SecurityUtil.getLoginCompanyId();
        if (StringUtils.isEmpty(query.getStartTime()) && StringUtils.isEmpty(query.getEndTime())) {
            LocalDate today = LocalDate.now();
            LocalDate oneMonthAgo = today.minusMonths(1);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            query.setStartTime(oneMonthAgo.format(formatter));
            query.setEndTime(today.format(formatter));
        }
        ReceiveCounts receiveCounts = repaymentOrderInfoMapper.getReceiveCounts(query, companyId, companyType);
        if (receiveCounts.getCertificationCounts() != 0) {
            BigDecimal divide = receiveCounts.getReceiveAmounts().divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
            receiveCounts.setReceiveAmounts(divide);
        }
        return receiveCounts;
    }

    /**
     * @description: 债权方账户-回款记录(平台资方共用)
     * @author: ZCH
     * @date: 2025/3/26 0026 21:02
     * @param: [dto]
     * @return: com.github.pagehelper.Page<com.xd.core.finance.vo.RepayManageVo>
     **/
    @Override
    public Page<RepayManageVo> getRepayManage(RepayManageDto dto) {
        String companyType = SecurityUtil.getLoginUser().getUser().getCompanyType();
        Integer companyId = null;
        List<Integer> userIds = null;
        if (companyType.equals(SysConstant.USER_COMPANY_TYPE_ONE) || companyType.equals(SysConstant.USER_COMPANY_TYPE_FOUR)) {
            companyId = dto.getCompanyId();
        } else if (companyType.equals(SysConstant.USER_COMPANY_TYPE_TOW)) {
            companyId = SecurityUtil.getLoginCompanyId();
            userIds = iSysUserService.getUserIdsByGroup();
        } else if (companyType.equals(SysConstant.USER_COMPANY_TYPE_THREE)) {//代理
            return null;
        }
        //开始分页
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        return repaymentOrderInfoMapper.getRepayManage(dto, companyId, userIds);
    }

    /**
     * @description: 债权方账户回款记录导出
     * @author: ZCH
     * @date: 2025/3/25 0025 10:08
     * @param: [dto, id]
     * @return: void
     **/
    @Override
    public void exportRepayManage(RepayManageDto dto, Integer id) {
        String name = "";
        if ("1".equals(dto.getPayPass())) {
            name = "通道一回款记录excel文件" + UUID.randomUUID().toString().replace("-", "");
        } else {
            name = "官方通道（标准）回款记录excel文件" + UUID.randomUUID().toString().replace("-", "");
        }
        Integer companyId = SecurityUtil.getLoginCompanyId();
        FileOutputStream fileOutputStream = null;
        MissionCenterInfo missionCenterInfo = new MissionCenterInfo();
        missionCenterInfo.setId(id);
        missionCenterInfo.setFileName(name + ".xlsx");
        String filePath = localPathDir + exportFile + "/" + companyId;
        File dirFile = new File(filePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        try {
            List<RowHeightColWidthModel> rowHeightColWidthList = new ArrayList<>();
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 0, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 1, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 2, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 3, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 4, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 5, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 6, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 7, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 8, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 9, 20));
            File file = new File(filePath + "/" + name + ".xlsx");
            fileOutputStream = new FileOutputStream(file);

            ExcelWriter write = EasyExcel.write(fileOutputStream, RepayManageVo.class).build();
            WriteSheet writeSheet = EasyExcel.writerSheet(name).registerWriteHandler(new CustomRowHeightColWidthHandler(rowHeightColWidthList)).build();
            dto.setPageSize(0);
            List<RepayManageVo> list = getRepayManage(dto);
            write.write(list, writeSheet);
            write.finish();
            fileOutputStream.flush();
            //修改文件状态 导出成功
            missionCenterInfo.setFileStatus(SysConstant.YSZT_FILE_STATUS_TOW);
            missionCenterInfo.setFileUrl(exportFile + "/" + companyId + "/" + name + ".xlsx");
            missionCenterInfoMapper.updateById(missionCenterInfo);
        } catch (Exception e) {
            //修改文件状态 导出失败
            missionCenterInfo.setFileStatus(SysConstant.YSZT_FILE_STATUS_THREE);
            missionCenterInfoMapper.updateById(missionCenterInfo);
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public OfflineRepaymentDetailVo getOfflineRepaymentDetail(OfflineRepaymentDetailQuery query) {
        OfflineRepaymentDetailVo vo = new OfflineRepaymentDetailVo();
        LambdaQueryWrapper<RepaymentOrderInfo> wrapper = new LambdaQueryWrapper<>();
        if (query.getFlag().equals("1")) {
            wrapper.eq(RepaymentOrderInfo::getOrderId, query.getOrderId());
            wrapper.eq(RepaymentOrderInfo::getType, "3");
        } else {
            wrapper.eq(RepaymentOrderInfo::getDebtId, query.getDebtId());
            wrapper.eq(RepaymentOrderInfo::getType, "6");
        }
        wrapper.in(RepaymentOrderInfo::getPayStatus, "1", "2");
        RepaymentOrderInfo repaymentOrderInfo = repaymentOrderInfoMapper.selectOne(wrapper);
        if (ObjectUtil.isNotEmpty(repaymentOrderInfo)) {
            vo.setOrderId(repaymentOrderInfo.getOrderId())
                    .setRepayBank(repaymentOrderInfo.getRepayBank())
                    .setRepayAccount(repaymentOrderInfo.getRepayAccount())
                    .setRepayName(repaymentOrderInfo.getRepayName());
        }
        return vo;
    }
}
